package com.hu.network.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;

/**
 * 说明：
 *
 * @author ： hucanhua
 * @date ： 2017/10/28
 */
public class NetUtil {
    public NetUtil() {
    }

    public static NetworkInfo isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            int length;
            if (Build.VERSION.SDK_INT >= 21) {
                Network[] info = cm.getAllNetworks();
                if (info != null) {
                    length = info.length;

                    for (int i = 0; i < length; ++i) {
                        Network network = info[i];
                        NetworkInfo networkInfo = cm.getNetworkInfo(network);
                        if (networkInfo.isAvailable()) {
                            return networkInfo;
                        }
                    }
                }
            } else {
                NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
                length = networkInfos.length;

                for (int i = 0; i < length; ++i) {
                    NetworkInfo networkInfo = networkInfos[i];
                    if (networkInfo.isAvailable()) {
                        return networkInfo;
                    }
                }
            }
        }

        return null;
    }

    public static boolean activeNetworkIsAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable();
    }

    public static boolean isWifiEnabled(Context context) {
        ConnectivityManager mgrConn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager mgrTel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return (mgrConn != null ? mgrConn.getActiveNetworkInfo() : null) != null && mgrConn.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED || (mgrTel != null ? mgrTel.getNetworkType() : 0) == 3;
    }

    public static boolean isWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm != null ? cm.getActiveNetworkInfo() : null;
        return networkINfo != null && networkINfo.getType() == 1;
    }

    public static boolean isMobilNet(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm != null ? cm.getActiveNetworkInfo() : null;
        return networkINfo != null && networkINfo.getType() == 0;
    }
}
